<?php

//
//  Created by Chagan Anton on 29.07.12.
//  Copyright Chagan Anton 2012. All rights reserved.
//
class AjaxController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to 'column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = 'ajax';

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }


    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        $this->render('index');
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    public function actionCreate_Msg() {
        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
        $model = new Msg;
        $model->andr = new Android;
        $model->iphone = new Iphone;
        $model->blckb = new Blackberry;
        // uncomment the following code to enable ajax-based validation

        if (isset($_POST['ajax']) && $_POST['ajax'] === 'msg-Create_Msg-form') {
            echo CActiveForm::validate($model);
            echo CActiveForm::validate($model, array($model->andr));
            //echo CActiveForm::validate($model,array($model->iphone));
            //echo CActiveForm::validate($model,array($model->blckb));

            Yii::app()->end();
        }


        if (isset($_POST['Msg']) || isset($_POST['Android']) || isset($_POST['Iphone']) || isset($_POST['Blackberry'])) {
            $model->attributes = $_POST['Msg'];
            $model->andr->attributes = $_POST['Android'];
            $model->iphone->attributes = $_POST['Iphone'];
            $model->blckb->attributes = $_POST['Blackberry'];
            /* if($model->validate() && $model->andr->validate())
              {
              // form inputs are valid, do something here
              if($model->save() && $model->andr->save()) echo "All fine!";
              return;
              } */

            if (isset($_POST['Android']) && $model->andr->save()) {
                echo "Android fine!";
                return;
            }
            if (isset($_POST['Iphone']) && $model->iphone->save()) {
                echo "iphone fine!";
                return;
            }
            if (isset($_POST['Blackberry']) && $model->blckb->save()) {
                echo "blckb fine!";
                return;
            }
        }

        //echo $model->findByPk(1)->android->content;
        $this->renderPartial('Create_Msg', array('model' => $model), false, false);
        //$this->render('Create_Msg',array('model'=>$model));
    }

    public function actionWho() {
        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
        //$this->render('Who');
        $this->renderPartial('Who', false, false);
    }

    public function actionWhen() {
        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
        //$this->render('When');
        $this->renderPartial('When', false, false);
    }

    public function actionConfirm() {
        // return results 0 - not authenticated
        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
        //var_dump($_POST);

        if (Yii::app()->user->checkAccess('createPUSH')) {

            //echo "Confirm =)";
            /* $model=new Msg;
              $model->andr= new Android;
              $model->andr->setscenario("search");
              $model->iphone= new Iphone;
              $model->iphone->setscenario("search");
              $model->blckb= new Blackberry;
              $model->blckb->setscenario("search");
              $model->attributes=$_POST['Msg'];
              $model->andr->attributes=$_POST['Android'];
              $model->iphone->attributes=$_POST['Iphone'];
              $model->blckb->attributes=$_POST['Blackberry']; */

            //echo $model->iphone->rich_notification_subject."   ";
            //echo $model->iphone->rich_notification_content;
            //if ($_POST['now'])
            if (isset($_POST['now'])) { //sending push now!
                $api = new xtifyApi("now");
                $api->nc->apiKey = "c49e69ac-6549-41d5-82ef-f88fee4bc6dc";
                if (Yii::app()->user->name == "dermapen")
                    $api->nc->appKey = "7d9d80b2-8385-4c31-a972-6709efcb267b";
                if (Yii::app()->user->name == "test") {
                    $api->nc->appKey = "12106832-219e-4acc-ae25-50f1fcd71c57";
                    $api->nc->apiKey = "9857088e-f090-49d7-91a6-06bd4883da55";
                }
                if (isset($_POST['male']))
                    array_push($api->nc->hasTags, "male");
                if (isset($_POST['female']))
                    array_push($api->nc->hasTags, "female");
                if (!isset($_POST['male']) && !isset($_POST['female'])) {
                    $api->nc->sendAll = true;
                    unset($api->nc->hasTags);
                    unset($api->nc->notTags);
                    unset($api->nc->xids);
//                    $api->nc->xids [] = '51604b97534c5cddc644680c';
                }
//                if ($_POST['msg_type'] == "rich")
//                    $api->iphone->action->type = "RICH";
//                $api->iphone->rich->action->type = "RICH";
                //==============================================================================================
//                    Filling model subject and content by POST parameters

                if (isset($_POST['android'])) {
                    $api->iphone->rich->message = $_POST['Android']['content'];
                    $api->iphone->rich->subject = $_POST['Android']['subject'];
                    $api->iphone->message = $_POST['Android']['content'];
                    $api->iphone->subject = $_POST['Android']['subject'];
                }
                if (isset($_POST['iphone'])) {
                    if (Yii::app()->user->name == "dermapen")
//                        $api->nc->appKey = "6e1b6beb-7b24-46e5-8644-b76b61aecc56";
                        $api->nc->appKey = "5e76d87e-b9b5-4d30-93d2-1bb77478321a";


                    if ($_POST['msg_type'] != "rich") {
//                        $api->iphone->rich->message = $_POST['Iphone']['notification_content'];
//                        $api->iphone->rich->subject = $_POST['Iphone']['rich_notification_subject'];
                        $api->iphone->message = $_POST['Iphone']['notification_content'];
//                        $api->iphone->subject = $_POST['Iphone']['rich_notification_subject'];
                        unset($api->iphone->rich);
                    } else {
                        $api->iphone->action->type = "RICH";
                        $api->iphone->rich->message = $_POST['Iphone']['rich_notification_content'];
                        $api->iphone->rich->subject = $_POST['Iphone']['rich_notification_subject'];
                        $api->iphone->message = $_POST['Iphone']['rich_notification_subject'];
                        $api->iphone->subject = $_POST['Iphone']['rich_notification_subject'];
                    }
                }
                if (isset($_POST['blackberry'])) {
                    $api->iphone->rich->message = $_POST['Blackberry']['notification_content'];
                    $api->iphone->message = $_POST['Blackberry']['notification_content'];
                }



                //==============================================================================================


                if (isset($_POST['android'])) {
                    if (Yii::app()->user->name == "dermapen")
                        $api->nc->appKey = "7d9d80b2-8385-4c31-a972-6709efcb267b"; if (!$api->msg->sendMessage())
                        echo 1;
                }
                if (isset($_POST['iphone'])) {
                    if (Yii::app()->user->name == "dermapen")
                        $api->nc->appKey = "5e76d87e-b9b5-4d30-93d2-1bb77478321a"; if (!$api->msg->sendMessage())
                        echo 1;
                }


                echo $api->msg->getAsJSON();
                //if (!$api->msg->sendMessage()) echo 1;

                Yii::app()->end();
            }
            // creating push notification configuration
            else
                $type = "notif_config";
            //echo $type;
            $api = new xtifyApi($type);
            $api->nc->apiKey = "c49e69ac-6549-41d5-82ef-f88fee4bc6dc";
            if (Yii::app()->user->name == "dermapen")
            // android dermapen
                $api->nc->appKeys["key"] = "7d9d80b2-8385-4c31-a972-6709efcb267b";
            else {
                // appcamel
                $api->nc->appKeys["key"] = "85dfa915-646c-4112-9c88-d5074b8f78eb";
                $api->nc->appKeys["key"] = "b07748ec-6600-49c8-9cb9-cf43b8c9ec1d";
            }
            if (Yii::app()->user->name == "dermapen")
                $api->nc->name = "default"; //$_POST['Android']->content;
            if (isset($_POST['male']))
                array_push($api->nc->hasTags, "male");
            if (isset($_POST['female']))
                array_push($api->nc->hasTags, "female");
            if (isset($_POST['android'])) {
                $api->android->message = $_POST['Android']['content'];
                $api->android->messageTitle = $_POST['Android']['subject'];
            }
            if (isset($_POST['iphone'])) {
                $api->iphone->message = $_POST['Iphone']['notification_content'];
                $api->iphone->richSubject = $_POST['Iphone']['rich_notification_subject'];
                $api->iphone->richContent = $_POST['Iphone']['rich_notification_content'];
            }
            if (isset($_POST['blackberry'])) {
                $api->blackberry->message = $_POST['Blackberry']['notification_content'];
            }
            $api->nc->name = $_POST['Iphone']['notification_content'];

            if (!empty($_POST['lat'])) {
                $api->nc->notificationLocations->location['name'] = $_POST['address'];
                $api->nc->notificationLocations->location['description'] = $_POST['address'];
                $api->nc->notificationLocations->location['address'] = $_POST['address'];
                $api->nc->notificationLocations->location['lat'] = $_POST['lat'];
                $api->nc->notificationLocations->location['lng'] = $_POST['lng'];
                $api->nc->notificationLocations->location['radius'] = $_POST['radius'];
            }
            else
                unset($api->nc->notificationLocations->location);




            //$st_date=strtotime($_POST["st_date"]." ".$_POST["st_h"].":".$_POST["st_m"]);
            //$end_date=strtotime($_POST["end_date"]." ".$_POST["end_h"].":".$_POST["end_m"]);

            $api->nc->notificationSchedules->schedule['startDate'] = $_POST["st_date"]; //date('m/d/Y', $st_date);//"01/01/2013"; //date_format($st_date, "m/d/Y");
            $api->nc->notificationSchedules->schedule['endDate'] = $_POST["end_date"]; //date('m/d/Y', $end_date);//"01/01/2013"; //$_POST["end_date"];
            $api->nc->notificationSchedules->schedule['startTime'] = $_POST["st_time"]; //date('H:i', $st_date);//"01:01";//date_format($st_date, "H:i");
            $api->nc->notificationSchedules->schedule['endTime'] = $_POST["end_time"]; // date('H:i', $end_date);//"02:01";//$_POST["st_date"];
            //echo $api->msg->getAsJSON();
            if ($_POST['now']) {
                Yii::app()->end();
            }

            //echo Yii::app()->user->name;
            $api->create();
            $id = $api->response->notificationConfigurationResponse->notificationId;
            if ($api->response->notificationConfigurationResponse->response == "ERROR") {
                echo ($api->response->notificationConfigurationResponse->message);
                Yii::app()->end();
            }
            //var_dump( $api->response);
            unset($api);
            $api = new xtifyApi($type);
            $api->nc->apiKey = "c49e69ac-6549-41d5-82ef-f88fee4bc6dc";
            $api->nc->id = $id;
            $api->activate();
            //$api->nc->id=$api->response->notificationId
            //echo json_encode($api->response);
            //echo $api->response->notificationConfigurationResponse->message;
            //echo "===========================";
            //$result=$msg->createMessage();
            //echo "===========================";
            if ($api->response->notificationConfigurationResponse->response == 'SUCCESS') {
                echo "1";
            }
            else
                echo "2"; //$api->response->notificationConfigurationResponse->message;
        }
        else
            echo "0";
    }

    public function actionGetDetails() {
        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
        $api = new xtifyApi("notif_config");
        $api->nc->apiKey = "c49e69ac-6549-41d5-82ef-f88fee4bc6dc";
        $api->nc->id = $_POST['id'];
        $api->detail();
        echo $api->response;
        //var_dump( $api->response);
    }

    public function actionDelete() {
        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
        $api = new xtifyApi("notif_config");
        $api->nc->apiKey = "c49e69ac-6549-41d5-82ef-f88fee4bc6dc";
        $api->nc->id = $_GET['id'];
        $api->delete();
        var_dump($api->response);
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        if (isset($_POST['ForgotPassForm'])) {
            Yii::app()->end();
        }

        if (!Yii::app()->user->isGuest) {
            $this->renderPartial('login_complete', false, false);
            Yii::app()->end();
        }
        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login()) {
                echo "Hello " . Yii::app()->user->name;
                Yii::app()->end();
            } else {
                echo "I'm sorry but I don't know you ):";
                Yii::app()->end();
            }
            //$this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form

        $this->renderPartial('login', array('model' => $model), false, true);
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        //echo "GoodBye ".Yii::app()->user->name;
        Yii::app()->user->logout();
        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
        $model = new LoginForm;
        $this->renderPartial('login', array('model' => $model), false, true);

        //$this->redirect(Yii::app()->homeUrl);
    }

    public function actionChoise_app() {
        Yii::app()->clientscript->scriptMap['jquery.js'] = false;

        $this->renderPartial('choise_app', false, false);
        //$this->render('choise_app');
    }

    private function sendCoupon($app, $render_html, $xid) {

        $api = new xtifyApi("now");
//        $api->iphone->payload = "{\"type\":1, \"coupon\":" . $render_html . "}";
        $api->iphone->message = "Congratulations!";
        $api->iphone->badge = "+1";
//        $api->iphone->subject = "subj Congratulations!";
//        data for iOS
//        $api->iphone->action->data = "{\"type\":1, \"coupon\":{\"id\":\"48\",\"status\":\"ok\",\"discount_value\":\" \",\"date_create\":\"2013-07-20\",\"ready\":0}}";
        $api->iphone->action->data = "{\"type\":1, \"coupon\":" . $render_html . "}"; //$api->iphone->payload;
        $api->nc->xids[] = $xid; //_GET["xid"];
        $api->nc->apiKey = $app->api_key;
        $appKey = json_decode($app->app_key);
        unset($api->nc->hasTags); // чистим лишнее
        unset($api->nc->notTags);
        unset($api->nc->sendAll);
        $result = false;


        //Android 
//        if ($appKey->android) {
//            $api->nc->appKey = $appKey->android; //"7d9d80b2-8385-4c31-a972-6709efcb267b";
//            if ($api->msg->sendMessage())
//                $result = true;
//        }
//        echo $result;
        // iOS
        if ($appKey->iOS) {
            $api->iphone->action->type = "CUSTOM";
            unset($api->iphone->payload);
            unset($api->iphone->rich);
            unset($api->iphone->subject);
//            unset($api->iphone->action->data);
//            $api->iphone->message = "Congratulations!"; 
            $api->nc->appKey = $appKey->iOS->production; //"6e1b6beb-7b24-46e5-8644-b76b61aecc56";
//            echo $api->msg->getAsJSON();
            if ($api->msg->sendMessage())
                $result = true;
        }
        $api->nc->appKey = $appKey->iOS->development;
        $api->msg->sendMessage();
//        echo $result;
//        return $result;
        return 1;
    }

    public function actionReadyCoupon() {
//        echo "ready!!!";
//        Yii::app()->end();
        $model = PushBack::model()->findbyPk($_GET['id']); // находим купон по ид

        $response = new pushResponse();
        $response->st = "ok";
        $response->count = $model->count;
        $response->dv = str_pad($model->discount_value, 2, "0", STR_PAD_LEFT);
        $response->dc = $model->date_create;
        $response->id = $_GET['id'];
        $response->ready = 1; //$model->ready;
        $context = json_decode($model->context);
        $response->bn = $context->bonusName;
        $render_html = json_encode($response);

        // Version 2
        echo $render_html; // выводим ответ на нттр; 
        Yii::app()->end();
        // End version 2

        $api = new xtifyApi("now");
        $api->nc->xids[] = $context->xid; // устанавливаем хид
        //$api->iphone->action->type="RICH";
        //$api->iphone->rich->action->type="RICH";
        //$api->iphone->rich->message=$render_html; //"coupon message to inbox from pushnack";
        //$api->iphone->rich->subject="Discount coupon";
        //$api->iphone->message=$render_html;
//        $api->iphone->payload = "{\"type\":1, \"coupon\":" . $render_html . "}"; // заполняем необходимые поля
//        $api->iphone->message = "You Won Playing Spin Discount";
//        $api->iphone->subject = "Congratulations!";
//        $api->iphone->action->data = $api->iphone->payload; //  настройка 
//        $api->iphone->action->type = "DEFAULT";


        $app = Apps::model()->find("userIdentifier='" . $context->userIdentifier . "'");
//        $appKey = json_decode($app->app_key);
//        echo $appKey->iOS->development; 
//        echo $api->nc->xids[0];
        $this->sendCoupon($app, $render_html, $context->xid);

        echo $render_html; // выводим ответ на нттр; 
    }

    public function actionPushback() {


        //for crossplatform request
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
        header('Access-Control-Allow-Headers: X-Requested-With');

        // if getting readed coupon
//        if ($_GET['id'])
//            $this->readyCoupon();
        // if id is not present  ==================================================
//        else
//


//        Turn on and of one coupon per device 
        $model = PushBack::model()->find("runtimeIdentifier='" . $_GET['runtimeIdentifier'] . "' AND bonus_name='" . $_GET['bonusName'] . "'"); //search previous coupon


        if (!$model || $_GET['gender'] == 3) { // if another coupon or it's first coupon
            $model = new PushBack;
            if ($_GET['gender'] == 3)
                $model->count = $_GET['count'] + 1;
        }
        else // if previous coupon is found
            $justResponse = TRUE;

        if ($model->count > 3) // if coupons reach limits
            $justResponse = TRUE;

        $app = Apps::model()->find("userIdentifier='" . $_GET['userIdentifier'] . "'");
        if ($app)
            $prog = PushProg::model()->findbyPk($app->pushback_programm_id);
        else
            $prog = PushProg::model()->findbyPk(4); //by default
        if ($justResponse) {

            // уже есть такой купон или превышен лимит 
            $response = new pushResponse(); // создаем ответ приложению
            $response->st = "R";
            $context = json_decode($model->context);
            $response->bn = $context->bonusName;
            $response->dv = " ";
            $response->dc = $model->date_create;
            $response->id = $model->id;
            $response->ready = $model->ready;
            if ($model->ready == '1')
                $response->dv = str_pad($model->discount_value, 2, "0", STR_PAD_LEFT);
            unset($response->maxCouponsCount);
            unset($response->count);
            echo json_encode($response);
            Yii::app()->end();
        } else {

            // расчет значения купона из параметров дисконтной программы
            $param = json_decode($prog->discount_param);
            $model = $this->calculateDiscountValue($param, $model);
            $prog->elapsed--;
            $prog->discount_param = json_encode($param);
            $model->context = json_encode($_GET); // сохранение в пушбэк параметров устройства
            $model->date_create = date("Y-m-d", time() + 60 * 60 * 24 * 30);
            $model->pushback_programm_id = $prog->id;
            $model->runtimeIdentifier = $_GET['runtimeIdentifier'];
            $model->bonus_name = $_GET['bonusName'];
            $model->save();
        }

        //        If webapp working on browser - not on device - end request
        if ($_GET["xid"] == "browser" || $_GET["xid"] == NULL) { // т.е. пуши без хида не создаются
            echo "bad xid";
            Yii::app()->end();
        }
        $response = new pushResponse(); // создаем ответ приложению
        $response->st = "ok";
//        If discount value of coupon was received только непонятно зачем это тут!
//        if ($model->ready == 0)
        $response->dv = " ";
//        else {
//            $response->discount_value = $model->discount_value;
//        }
        $response->dc = $model->date_create;
        $response->id = $model->id;
        $response->ready = $model->ready;
        $response->count = $model->count;
        $response->bn = $_GET['bonusName'];
        unset($response->maxCouponsCount);
        unset($response->count);
        $render_html = json_encode($response);

        // отправка купона по пуш
//        $api = new xtifyApi("now");
//        $api->iphone->payload = "{\"type\":1, \"coupon\":" . $render_html . "}";
//        $api->iphone->message = "Congratulations!";
//        $api->iphone->subject = "Discount coupon";
//        $api->iphone->action->data = $api->iphone->payload;
//        $api->nc->xids[] = $_GET["xid"];
        //$api->iphone->action->type="RICH";
        //$api->iphone->rich->action->type="RICH";
        //$api->iphone->rich->message=$render_html; //"coupon message to inbox from pushnack";
        //$api->iphone->rich->subject="Discount coupon";
//        if (
        // Sending thru push
//        $this->sendCoupon($app, $render_html, $_GET["xid"]);
//                ) { // отправляем купон

        $prog->save(); // сохранение программы           
        echo $render_html; // вывод ответа
//        } else 
//     echo '0';
    }

    private function calculateDiscountValue($param, $model) {
        //!!!!!!!
        /* while($prog->elapsed)
          { */
        //choise discount values between from numbers
        if ($param->suit_or_rand * 100 > rand(0, 100) && $param->count > 0) {
            //generated numbers in table
            $t = rand(0, $param->count);
            //var_dump($param->suit);
            //echo $t; //echo $$t;
            //echo $param->suit[$t];
            $model->discount_value = $param->suit[$t];
            array_splice($param->suit, $t, 1);
            $param->count--;
        } else {
            //generate numbers from predefault values
            //echo "5-18";
            $t = floor(rand(1, 4));
            //echo $t;
            switch ($t) {
                case 4: $model->discount_value = "07";
                    $param->par->p5--;
                    break;
                case 1: $model->discount_value = "06";
                    $param->par->p6--;
                    break;
                case 2: $model->discount_value = "12";
                    $param->par->p12--;
                    break;
                case 3: $model->discount_value = "13";
                    $param->par->p18--;
                    break;
            }
        }

        //!!!!!!!
        /* echo $model->discount_value."<br>";
          }
          Yii::app()->end(); */

        return $model;
    }

    public function actionCoupon() {
        //ONly for DERMAPEN test===================================================
        $app = Apps::model()->find("userIdentifier='" . $_GET['userIdentifier'] . "'");
        if ($app)
            $prog = PushProg::model()->findbyPk($app->pushback_programm_id);
        else
            $prog = PushProg::model()->findbyPk(4); //by default
        $param = json_decode($prog->discount_param);
        if ($_GET['id']) {
            $model = PushBack::model()->findbyPk($_GET['id']);
            $this->renderPartial('coupon', array('model' => $model), false, false);
            Yii::app()->end();
        }
        // if id is not present
        else
            $model = new PushBack;
        //!!!!!!!
        $summ = 0;
        while ($prog->elapsed) {




            if ($param->suit_or_rand * 100 > rand(0, 100) && $param->count > 0) {
                $t = rand(0, $param->count);
                //var_dump($param->suit);
                //echo $t; //echo $$t;
                //echo $param->suit[$t];
                $model->discount_value = $param->suit[$t];
                array_splice($param->suit, $t, 1);
                $param->count--;
            } else {
                //echo "5-18";
                //echo $t;
                if ($param->par->p5 > 0 && $param->par->p6 > 0 && $param->par->p12 > 0 && $param->par->p18 > 0) {
                    while (r == "repeat") {
                        $t = floor(rand(1, 4));
                        switch ($t) {
                            case 4: $model->discount_value = 07;
                                if ($param->par->p5 < 1) {
                                    $r = "repeat";
                                    break;
                                }
                                $param->par->p5--;
                                $r = "exit";
                                break;
                            case 1: $model->discount_value = 06;
                                if ($param->par->p6 < 1) {
                                    $r = "repeat";
                                    break;
                                }
                                $param->par->p6--;
                                $r = "exit";
                                break;
                            case 2: $model->discount_value = 12;
                                if ($param->par->p12 < 1) {
                                    $r = "repeat";
                                    break;
                                }
                                $param->par->p12--;
                                $r = "exit";
                                break;
                            case 3: $model->discount_value = 13;
                                if ($param->par->p18 < 1) {
                                    $r = "repeat";
                                    break;
                                }
                                $param->par->p18--;
                                $r = "exit";
                                break;
                        }
                    }
                }
            }
            $prog->elapsed--;
            //!!!!!!!
            echo $model->discount_value . "<br>";
            $summ+=$model->discount_value;
        }
        echo "Summ=" . $summ . "<br>" . "aver=" . $summ / 1000;
        Yii::app()->end();
    }

    public function actionCouponAjax($id) {
        $model = PushBack::model()->find("code=" . $id);
        $resp['disc_value'] = $model->discount_value;
        echo json_encode($resp);
    }

    function in($time, $start, $end) {
        return $start <= (int) $time && (int) $time <= $end;
    }

    public function actionForgot_password() {
        if (isset($_POST['LoginForm'])) {
            Yii::app()->end();
        }
        Yii::app()->clientscript->scriptMap['jquery.js'] = false;

        $model = new ForgotPassForm();

        if (isset($_POST['ForgotPassForm'])) {
            $model->attributes = $_POST['ForgotPassForm'];
            echo $model->findUser();
            Yii::app()->end();
        }

        $this->renderPartial('forgot_password', array('model' => $model), false, true);
    }

    public function actionPush_button() {
        if (!Yii::app()->user->isGuest) {
            $this->renderPartial('push_button', false, false);
        }
    }

}
